Skip to content

feat(gateway): forward a streamed Chat reply while it arrives when Core permits early release - #3035

Open
jasper-yl wants to merge 4 commits into
oceanbase:masterfrom
jasper-yl:feat/gateway-live-stream
Open

jasper-yl wants to merge 4 commits into
oceanbase:masterfrom
jasper-yl:feat/gateway-live-stream

Conversation

@jasper-yl

Copy link
Copy Markdown
Contributor

Which issue or RFC does this PR close?

Implements the Chat Completions part of delivery item 7 of the RFC in #3003 (live streaming in disabled protection mode), on the two design points agreed in this comment. It does not close the RFC. The Responses route is not changed here; see "Not in this PR".

Rationale for this change

The gateway releases a reply only after it is complete and before_release has allowed it. A streaming client therefore sees nothing until the model has finished: 11–17 s for the turns measured in #3003. In disabled mode Core inspects no response, so this wait protects nothing.

What changes are included in this PR?

Core. An allowed before_send returns early_release: true while the protection mode is disabled. It permits the executor to forward the response of that one request while it arrives; before_release with the complete response is still required and still correlates it with the request binding. shadow, advisory and enforcing do not return the field. This is an additive field on ContextCheckResult in openapi/powercontext.yaml.

Gateway. With that permission, a stream: true request on /gateway/v1/chat/completions to an API-key upstream is forwarded to the client as the provider writes it (HTTP 200 with text/event-stream only; the bytes are unchanged). The gateway still buffers the reply and runs the release check and capture afterwards.

  • The transport hands chunks to a bounded channel carried by the admitted send, so the permission is settled before any byte is forwarded. A slow client slows the read from the provider.
  • The connection driver owns such an execution and polls it beside Hyper, without a detached task. The response body ends with the upstream body.
  • A client that disconnects before the provider has finished cancels the call (request_cancelled, no capture), as today.
  • Once the client has been handed data: [DONE] or the whole upstream body, its disconnect does not cancel the call. The release record and capture get up to 20 seconds after the connection ends, within the 180-second deadline and the shutdown drain limit, and the model permit stays held until they finish or are stopped.
  • If the provider stops mid-reply, the client connection ends abnormally instead of with a clean end of stream.
  • A forwarded reply over the response buffer limit is forwarded to its end; it is not captured and the call is recorded as withheld with buffer_limit_exceeded.
  • A gateway that discovered an enforcing Core at startup ignores the permission.
  • Call evidence gains early_release, true when content was forwarded early. first_model_content is located in the frames as they pass.

Everything else is released only when complete, as before: the Responses route, OAuth subscriptions, provider errors, non-streamed replies, and every mode other than disabled.

Are there any user-facing changes?

Yes. With Core in disabled mode (the default), streamed Chat Completions replies through the gateway now arrive incrementally. No configuration is added. The check result and the gateway call record each gain one additive field. Docs updated in both languages: operate/context-protection.md, operate/deploy-server.md (new "Streamed replies" section), operate/gateway-evidence.md.

A reply that was already forwarded cannot be recalled if the release check then fails or Core becomes unavailable; the call record shows that outcome and the turn is not captured. In disabled mode the release check inspects no content, so this is limited to binding correlation and Core availability.

How was this change tested?

Linux x86_64.

  • cargo test --workspace --no-fail-fast in gateway/ with PC_TEST_PYTHON set (real-Core tests included): all pass. New: pc-gateway-app/tests/live_streaming.rs (7 tests against the real binary, with a provider whose body the test writes step by step) and pc-gateway-transport/tests/live_output.rs (3 tests). Two of the new tests fail when the completion tracking is disabled, which I checked by removing it.
  • cargo fmt --all -- --check passes. cargo clippy --workspace --all-targets reports one warning in gateway_behaviors.rs that is also on master, none in changed code.
  • pytest tests/builtin/runtime/test_context_check.py tests/e2e/test_context_check_authorization.py tests/test_api_contract.py tests/test_js_operations.py tests/test_desktop_contract.py: pass. generate_api.py --check, generate_js_operations.py --check, ruff check, ruff format --check pass. Desktop bindings regenerated; export_ipc -- --check passes.
  • make docs-test passes (1,584 pages and their internal links).
  • Desktop qualification sqlite-early-release-16e1cb20-v1: the native probe passed the anonymous loopback, static Bearer, HTTPS with base path, and Provider modes against the wheel built from 16e1cb206.

Real provider (gpt-4.1-mini on api.openai.com, Core and pc-gateway built from this branch, a 300-line reply of 188 KB):

Mode, client behaviour First body byte Captured
disabled, reads to the end (3 runs) 0.41–1.62 s of 9.4–11.5 s 3 of 3
disabled, closes at [DONE] (3 runs) 0.43–0.79 s 3 of 3
disabled, closes after 20 reads (2 runs) 0.39–0.44 s 0 of 2, calls request_cancelled
shadow, reads to the end (2 runs) 9.2 s and 10.4 s, the whole reply at once 2 of 2

Not run: macOS, Windows; DSH as the client; a provider other than OpenAI; the full Python suite (the Python change is one field in check_context).

Not in this PR

The Responses route still sends upstream without streaming and replays the complete reply. Forwarding it live needs the upstream request rendered with stream: true before before_send, because the binding covers the exact payload, so the gateway must know before the check that early release is likely. My suggestion is an optional early_release hint in ContextProtectionCapabilities, read at startup like enforcing, with the per-request permission staying authoritative; an unpermitted streamed reply would be buffered, converted to the terminal response and replayed as today. I would like a maintainer's view on that before changing the capabilities contract. The DSH route in #3020 prefers Responses, so it gets live output only with that follow-up.

AI usage statement

Written with Claude Code (Claude). I reviewed the change and ran the tests and provider runs listed above.


中文摘要:实现 #3003 RFC 第 7 项中 Chat Completions 路由的部分。Core 在保护模式为 disabled 时,在准许的 before_send 结果里返回 early_release: true;gateway 据此把流式的 Chat 回复在到达时就转发给客户端,放行记录与沉淀在客户端拿到回复之后完成。客户端在上游结束前断开,调用取消;客户端拿到 data: [DONE] 或全部正文之后断开,不再取消调用,剩余工作在连接结束后最多 20 秒内完成,期间保持模型并发许可。上游中途停止时异常结束客户端连接。真实供应商上首个正文字节 0.41–1.62 秒到达(此前要等整轮结束),客户端在 [DONE] 处断开时 3/3 完成沉淀。Responses 路由未改,需要先确定 gateway 在渲染前如何得知可以向上游请求流式,正文里给出了建议。

🤖 Generated with Claude Code

jasper-yl and others added 3 commits December 3, 2026 20:45
…protection is disabled

An allowed before_send returns early_release: true when the protection mode
is disabled. That mode inspects no response, so an executor may forward the
response of that request to its caller while it arrives. before_release with
the complete response is still required and correlates it with the request
binding. The other modes do not return the field.

Co-Authored-By: Claude <noreply@anthropic.com>
…re permits it

With the early release permission from before_send, a streamed Chat
Completions reply from an API-key upstream reaches the client as the provider
writes it. The gateway keeps buffering the reply, and the release check and
capture run after the client has it.

The connection driver owns such an execution. The response body ends with the
upstream body; a client that disconnects before that cancels the call, and a
client that closes once it has the end of the stream does not: the remaining
work finishes within a grace period while the model permit stays held. An
upstream that stops mid-reply ends the client connection abnormally.

Co-Authored-By: Claude <noreply@anthropic.com>
The native probe selected sqlite-early-release-16e1cb20-v1 against the SQLite
Server wheel built from 16e1cb2 and passed the anonymous loopback, static
Bearer, HTTPS with base path, and Provider modes.

Co-Authored-By: Claude <noreply@anthropic.com>

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The live response path introduces an unbounded SSE event buffer. The inline finding was reproduced against the real Gateway binary with a controlled upstream; please have the Gateway owner assess it.

return Poll::Ready(None);
};
// A client may close as soon as it reads the protocol end; from here on that is not a cancellation.
self.framer.push(&chunk);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Bound the SSE parser used to detect stream completion

SseFramer::push retains every byte until an SSE blank-line delimiter arrives. Unlike the old buffered path, the new live transport continues forwarding after its 1 MiB response buffer limit, so a large or unterminated event keeps growing this second buffer without a bound. Against the real Gateway binary, after forwarding 4 MiB without an event terminator, RSS increased from 14,328 to 18,968 KiB while the upstream was still open; the transport ceiling did not bound retained response data. The bounded chunk channel does not help because this parser consumes and retains its chunks. Detect the terminal marker with bounded state, or enforce an explicit event-size limit without accumulating an unbounded provider response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and fixed in 96738a4. The live body no longer uses SseFramer. It scans lines and keeps at most the first 16 bytes of the current line plus three flags, which is enough to recognise an event whose only data is [DONE] (LF or CRLF, split across chunks in any way).

Measured on Linux x86_64 with the real binary and a provider that sends 16 MiB after data: with no event terminator, all of it read by the client: gateway RSS 17,180 kB before and 18,076 kB after.

Tests added: one for the scanner (split chunks, CRLF, a 4 KiB event before the marker, [DONE] inside other data), and a process test in which a 2 MiB event is forwarded, the client closes at [DONE], and the call ends withheld without an interruption. cargo test -p pc-gateway-app passes.

中文:问题属实,已在 96738a4 修复。流式响应体不再使用 SseFramer,改为按行扫描,只保留当前行的前 16 个字节和三个标志位。用真实二进制实测,上游发送 16 MiB 且不带事件结束符时,gateway 的 RSS 从 17,180 kB 变为 18,076 kB。

… events

The live response body used the SSE framer to notice `data: [DONE]`. The
framer keeps every byte until an event ends, and a forwarded reply is not
limited by the response buffer, so one large or unterminated event grew
that buffer with the reply. The body now scans lines with a fixed-size
state.

Co-Authored-By: Claude <noreply@anthropic.com>
@hireview001 hireview001 added module:core Core: PR changes under src/ module:desktop Primary module: desktop app and platform integration module:gateway Primary module: model gateway, protocols and context injection labels Dec 4, 2026
@hireview001

Copy link
Copy Markdown
Collaborator

The affected modules are Gateway, Desktop, Core. @frf12, please coordinate follow-up. Gateway: @frf12 @happy-v587 @NeverENG; Desktop: @PsiACE @knqiufan; Core: @hidb4ai @frf12 @Fengzdadi @beatenevo. Please coordinate the review of the affected changes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:core Core: PR changes under src/ module:desktop Primary module: desktop app and platform integration module:gateway Primary module: model gateway, protocols and context injection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants